package com.sh.data.engine.velocity.tool;

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.tools.Scope;
import org.apache.velocity.tools.config.DefaultKey;
import org.apache.velocity.tools.config.InvalidScope;
import org.apache.velocity.tools.generic.SafeConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;

@DefaultKey("jsonpath")
@InvalidScope({Scope.APPLICATION, Scope.SESSION})
public class JsonPathTool extends SafeConfig implements Serializable {

    private static final Logger logger = LoggerFactory.getLogger(JsonPathTool.class);

    public static Object parse(String json, String jsonpath) {
        if (jsonpath.startsWith("&")) {
            jsonpath = jsonpath.replaceFirst("&", "");
        }
        // logger.info("jsonpath:{}",jsonpath);
        if (StringUtils.isBlank(json)) {
            return null;
        }
        if (StringUtils.isBlank(jsonpath)) {
            return null;
        }
        Object obj = JsonPath.using(Configuration.defaultConfiguration()).parse(json).read(jsonpath);
        return obj;
    }
}
